<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <div class="version">
      <el-select
        placeholder=""
        v-model="bb"
        :disabled="!isDetail"
        @change="handleChangeVersion"
      >
        <el-option
          v-for="item in bbOptions"
          :key="item.pkid"
          :label="item.batch"
          :value="item.pkid"
        >
        </el-option>
      </el-select>
    </div>

    <div class="tabs">
      <div
        class="tabs-item"
        :class="{ active: currentTab === index }"
        v-for="(item, index) of tabs"
        :key="index"
        @click="handleChangeTab(item, index)"
      >
        {{ item }}
      </div>
    </div>
    <div class="body">
      <BaseInfo
        ref="baseInfoRef"
        :isDetail="isDetail"
        :detailInfo="baseInfo"
        v-show="currentTab === 0"
        @changeTime="handleChangeTime"
        @changeProjectName="handleChangeProjectName"
        @changeInvestment="handleChangeInvestmen"
      />
      <YearInfo
        ref="yearInfoRef"
        :isDetail="isDetail"
        :yearList="yearList"
        :detailInfo="yearInfo"
        v-show="currentTab === 1"
        @changeYearPlanInvestment="
          handleChangeYearPlanInvestment
        "
      />
      <PlanInfo
        ref="planInfoRef"
        :isDetail="isDetail"
        :yearList="yearList"
        :detailInfo="planInfo"
        :projectName="projectName"
        :yearPlanInvestment="yearPlanInvestment"
        v-show="currentTab === 2"
      />
      <ProcessInfo
        ref="processInfoRef"
        :isDetail="isDetail"
        :yearList="yearList"
        :monthList="monthList"
        :detailInfo="processItemInfos"
        :projectName="projectName"
        :investment="investment"
        :yearPlanInvestment="yearPlanInvestment"
        v-show="currentTab === 3"
      />
    </div>
    <div class="line" v-show="!isDetail">
      <el-button
        @click="saveInfo"
        class="save-btn"
        :loading="btnLoding"
        >保存</el-button
      >
    </div>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import BaseInfo from './components/baseInfo.vue'
import YearInfo from './components/yearInfo.vue'
import PlanInfo from './components/planInfo.vue'
import ProcessInfo from './components/processInfo.vue'
import {
  addProjectInfo,
  queryProjectDetail,
  queryHistoryList,
  queryHistory
} from '@/api/keyProjectManagement'

export default {
  props: {
    pkid: String,
    title: String,
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Breadcrumb,
    BaseInfo,
    YearInfo,
    PlanInfo,
    ProcessInfo
  },
  data() {
    return {
      tabs: [
        '项目基础信息',
        '项目年度信息',
        '项目计划信息',
        '项目进度信息'
      ],
      currentTab: 0,
      loading: false,
      btnLoding: false,
      resultArr: [],
      formArr: [
        'baseInfoRef',
        'yearInfoRef',
        'planInfoRef',
        'processInfoRef'
      ],

      baseInfo: {},
      planInfo: [],
      processItemInfos: [],
      yearInfo: [],

      projectName: '',
      investment: 0,
      yearPlanInvestment: {},
      yearList: [],
      monthList: [],

      bb: '',
      bbOptions: []
    }
  },
  computed: {
    titles() {
      return [this.title]
    }
  },
  mounted() {
    if (this.isEdit) {
      this.getDetailInfo()
      this.getHistroyList()
    }
  },
  methods: {
    // 切换tab
    handleChangeTab(item, index) {
      if (index !== 0) {
        if (!this.yearList || this.yearList.length === 0) {
          this.$message.warning('请选择项目年度')
          return
        }
      }
      this.currentTab = index
    },

    // 获取项目详情
    getDetailInfo() {
      this.loading = true
      queryProjectDetail(this.pkid).then((res) => {
        if (res.success) {
          this.handleDetail(res)
        } else {
          this.$message.error(res.message)
        }
        this.loading = false
      })
    },
    // 获取项目详情历史
    getDetailInfoHistroy(refId) {
      this.loading = true
      queryHistory(refId).then((res) => {
        if (res.success) {
          this.handleDetail(res)
        } else {
          this.$message.error(res.message)
        }
        this.loading = false
      })
    },

    // 处理详情
    handleDetail(res) {
      // 处理基本信息
      res.data.baseInfo.departId = res.data.baseInfo
        .departId
        ? res.data.baseInfo.departId.split(',')
        : []
      res.data.baseInfo.permissionUser = res.data.baseInfo
        .permissionUser
        ? res.data.baseInfo.permissionUser.split(',')
        : []
      res.data.baseInfo.filterYear = res.data.baseInfo
        .filterYear
        ? res.data.baseInfo.filterYear.split(',')
        : []
      this.baseInfo = res.data.baseInfo
      // 处理年度计划信息
      this.yearInfo = res.data.yearInfo
      res.data.yearInfo.forEach((item) => {
        this.yearPlanInvestment[item.year] =
          item.planInvestment
      })
      // 处理项目计划信息
      const planInfo = []
      if (
        res.data.planInfo &&
        res.data.planInfo.length > 0
      ) {
        res.data.planInfo.forEach((item) => {
          planInfo.push({
            ...item.industryPlanInfo,
            workInfos: item.workInfos
          })
        })
      }

      this.planInfo = planInfo
      // 处理项目进度信息
      let processItemInfos = JSON.parse(
        JSON.stringify(res.data.processItemInfos)
      )
      processItemInfos.forEach((item) => {
        const imgList = []
        const videoList = []
        let imgFile = {}
        item.attachmentList.forEach((file) => {
          item.fileList = []
          item.imgPkid = ''
          item.fileId = ''
          item.fileName = ''
          if (file.type === 'other') {
            imgFile = file
          } else if (file.type === 'picture') {
            imgList.push({
              pkid: file.pkid,
              attachmentId: file.fileId,
              fileName: file.fileName
            })
          } else {
            videoList.push({
              pkid: file.pkid,
              attachmentId: file.fileId,
              fileName: file.fileName
            })
          }
        })
        item.fileId = imgFile.fileId
        item.fileName = imgFile.fileName
        item.imgPkid = imgFile.pkid
        item.imgList = imgList
        item.videoList = videoList
        delete item.attachmentList
        item.innovationPoint = item.innovationPoint
          ? item.innovationPoint.split(',')
          : []
      })
      this.processItemInfos = processItemInfos

      this.$nextTick(() => {
        this.handleChangeTime(this.baseInfo.filterYear)
      })

      this.projectName = res.data.baseInfo.projectName
      this.investment = res.data.baseInfo.investment || 0
    },

    // 修改时间
    handleChangeTime(val) {
      const years = []
      const months = []
      val.forEach((year) => {
        years.push(year)
        this.yearPlanInvestment[year] =
          this.yearPlanInvestment[year] || 0
        const monthItem = []
        for (let j = 1; j < 13; j++) {
          monthItem.push(j)
        }
        months.push(monthItem)
      })
      this.yearList = years
      this.monthList = months
    },
    // 修改项目名称
    handleChangeProjectName(val) {
      this.projectName = val
    },
    // 修改总投资
    handleChangeInvestmen(val) {
      this.investment = val
    },
    // 修改年度投资
    handleChangeYearPlanInvestment(year, val) {
      this.yearPlanInvestment[year] = val || 0
      console.log(
        'this.yearPlanInvestment',
        this.yearPlanInvestment
      )
    },

    // 点击保存
    saveInfo() {
      this.btnLoding = true
      this.resultArr = []
      for (let i = 0; i < this.formArr.length; ++i) {
        this.checkForm(this.formArr[i], i)
      }
      const that = this
      Promise.all(that.resultArr)
        .then(() => {
          // 基础信息
          const baseInfo = JSON.parse(
            JSON.stringify(that.$refs.baseInfoRef.basicForm)
          )
          baseInfo.departId = baseInfo.departId.join(',')
          baseInfo.permissionUser =
            baseInfo.permissionUser.join(',')
          baseInfo.filterYear =
            baseInfo.filterYear.join(',')
          // delete baseInfo.approveFileList
          // 年度信息
          const yearInfo = JSON.parse(
            JSON.stringify(
              that.$refs.yearInfoRef.basicForm.yearInfo
            )
          )
          // 计划信息
          const planInfo = []
          const planInfo1 = JSON.parse(
            JSON.stringify(
              that.$refs.planInfoRef.basicForm.planInfo
            )
          )
          planInfo1.forEach((item) => {
            const industryPlanInfo = JSON.parse(
              JSON.stringify(item)
            )
            delete industryPlanInfo.workInfos
            const workInfos = item.workInfos
            planInfo.push({
              industryPlanInfo: industryPlanInfo,
              workInfos: workInfos
            })
          })
          // 进度信息
          const processItemInfos = JSON.parse(
            JSON.stringify(
              that.$refs.processInfoRef.basicForm
                .processItemInfos
            )
          )
          processItemInfos.forEach((item) => {
            const attachmentList = []
            if (item.fileId) {
              attachmentList.push({
                pkid: item.imgPkid,
                type: 'other',
                fileId: item.fileId
              })
            }
            if (item.imgList) {
              item.imgList.forEach((img) => {
                attachmentList.push({
                  pkid: img.pkid,
                  type: 'picture',
                  fileId:
                    img.attachmentId || img.response.data
                })
              })
            }
            if (item.imgList) {
              item.videoList.forEach((video) => {
                attachmentList.push({
                  pkid: video.pkid,
                  type: 'video',
                  fileId:
                    video.attachmentId ||
                    video.response.data
                })
              })
            }
            item.attachmentList = attachmentList
            item.innovationPoint =
              item.innovationPoint.join(',')
            delete item.fileList
            delete item.imgList
            delete item.videoList
          })
          const formData = {
            baseInfo: baseInfo,
            yearInfo: yearInfo,
            planInfo: planInfo,
            processItemInfos: processItemInfos
          }
          try {
            addProjectInfo(formData).then((res) => {
              if (res.success) {
                that.$message.success('保存成功')
                this.$router.push({
                  path: '/wisdomIndustry/KeyProjectManagement/list',
                  query: { refresh: Date.now() }
                })
              } else {
                that.$message.error(
                  res.message || '保存失败'
                )
              }
              that.btnLoding = false
            })
          } catch (error) {
            console.log(error)
          }
        })
        .catch((errIndex) => {
          console.log('error', errIndex)
          that.currentTab = errIndex
          that.btnLoding = false
          that.$message.warning('请正确填写表单')
        })
    },
    // 表单校验
    checkForm(formName, index) {
      const that = this
      const result = new Promise((resolve, reject) => {
        that.$refs[formName].$refs.basicFormRef.validate(
          (valid) => {
            if (valid) {
              resolve()
            } else {
              reject(index)
            }
          }
        )
      })
      that.resultArr.push(result)
    },

    // 获取更新列表
    getHistroyList() {
      queryHistoryList({
        refId: this.pkid,
        pageNo: 1,
        pageSize: 9999
      }).then((res) => {
        if (res.success && res.data) {
          this.bbOptions = res.data.list
          this.bb = this.pkid
          this.bbOptions.push({
            pkid: this.pkid,
            batch: '最新版本'
          })
        }
      })
    },

    // 切换版本
    handleChangeVersion(refId) {
      if (refId === this.pkid) {
        this.getDetailInfo()
      } else {
        this.getDetailInfoHistroy(refId)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  position: relative;
  .tabs {
    width: 100%;
    height: 50px;
    border-bottom: 1px solid #f1f1f1;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    &-item {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 150px;
      height: 100%;
      font-size: 16px;
      font-weight: 500;
      color: #4c565c;
      position: relative;
      cursor: pointer;
      &::before {
        position: absolute;
        content: ' ';
        right: 0;
        top: 19px;
        width: 1px;
        height: 12px;
        background: #d0d8e1;
      }
      &:last-child {
        &::before {
          display: none;
        }
      }
      &.active {
        color: #497fa3;
        &::after {
          position: absolute;
          content: ' ';
          bottom: 0;
          left: 62px;
          width: 26px;
          height: 3px;
          background: #497fa3;
          border-radius: 2px;
        }
      }
    }
  }

  .version {
    position: absolute;
    top: 10px;
    right: 20px;
    ::v-deep {
      .el-select {
        width: 150px !important;
      }
      .el-input {
        width: 150px !important;
      }
      .el-input__inner {
        width: 150px !important;
        border: none !important;
        text-align: right;
      }
      .el-input__suffix {
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .el-input.is-disabled .el-input__inner {
        background: transparent !important;
      }
    }
  }
}
</style>
